package org.example;

import com.mysql.cj.xdevapi.Client;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;

public class TestServer1 {
    private static String PORT;
    private static String ADDRESS;

    public static void main(String[] args) throws IOException {
        // 远程服务端的文件存储目录路径
        proper();
        try {
            // 创建服务端Socket并绑定端口
            ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT));
            System.out.println("服务端已启动，等待文件接收...");

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接：" + clientSocket.getInetAddress().getHostAddress());

                // 接收文件类型
                String fileType = receiveString(clientSocket);
                String[] requestParts = fileType.split(" ");
                String requestType = requestParts[0];
                String FileName = requestParts[1];
                // 接收文件内容
                byte[] fileContent = receiveBytes(clientSocket);
                if(requestType.equals("DELETE")){
                    deleteFile(FileName);
                    System.out.println("服务端成功删除文件: " + FileName);
                }else if(requestType.equals("UPLOAD")){
                    // 保存文件到指定路径
                    String filePath = ADDRESS + File.separator + FileName;
                    saveFile(filePath, fileContent);

                    System.out.println("文件接收成功：" + filePath);
                    // 关闭客户端Socket连接
                    clientSocket.close();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void deleteFile(String fileName) {
        String serverDirectory = ADDRESS;
        String serverFilePath = serverDirectory + "/" + fileName;

        try {
            // 在服务端删除相同的文件
            Path serverPath = Paths.get(serverFilePath);
            Files.deleteIfExists(serverPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void proper() throws IOException {
        //读取properties
        InputStream inputStream = Client.class.getClassLoader().getResourceAsStream("server.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        PORT = properties.getProperty("port");
        ADDRESS = properties.getProperty("address");
        inputStream.close();
    }

    private static String receiveString(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        return reader.readLine();
    }

    private static byte[] receiveBytes(Socket socket) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;
        InputStream inputStream = socket.getInputStream();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        return byteArrayOutputStream.toByteArray();
    }

    private static void saveFile(String filePath, byte[] fileContent) throws IOException {
        Path path = Path.of(filePath);
        Files.write(path, fileContent, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }
}

